/**
 * Copyright (c) 2021 zhaodongyang
   Ohos-Coverflow_JS is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2.
   You may obtain a copy of Mulan PSL v2 at:
            http://license.coscl.org.cn/MulanPSL2
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
   See the Mulan PSL v2 for more details.
 */
import {config} from "../config.js"
import {scrollParam} from "../scrollParam.js"
import TypeEnum from "../TypeEnum.js"

export default {
    private: {
        lists: new Array(), // 虽然只用到了lists的长度length，但是diyswiper.hml里面的for循环用到了lists，不可以直接改为数字
        showData: {
            lastShow: -1,
            currentShow: -1,
            nexttShow: -1,
        }, // 虽然只用到了lists的长度length，但是diyswiper.hml里面的for循环用到了lists，不可以直接改为数字
        centerX: 0,
        itemWidth: 0,
        itemSpace: 0,
        percent: 80,
        margin: 0,
        scale: 0,
        localId: "",
        startX: 0,
        startY: 0,
        canNotScroll: false,
        isUnionScroll: false
    },
    public: {
        currentPage: 0,
    },
    props: {
        cacheSize: 1,
        currentIndex: 0,
        itemPercent: {
            default: 80
        },
        itemMargin: {
            default: 10
        },
        swiperDatas: new Array(),
        diyId: {
            default: "defaultId"
        },
    },
    itemAnimator(e) {
        if (e == null || e == undefined || e.detail == null || e.detail == undefined) {
            return
        }
        let data = e.detail
        this.$emit("itemEvent", data)
    },
    onReady() {
        this.initData()
    },
    onShow() {
        const ctx = this
        setTimeout(function () {
            try {
                let listView = ctx.$element("list-view")
                let option = new config(TypeEnum.data.TYPE_SEND_PARENT_WIDTH, ctx.currentPage, ctx.itemWidth, {}, {
                    id: ctx.localId,
                    parentWidth: listView.getBoundingClientRect().width
                })
                ctx.$emit("eventType1", option)

                ctx.scrollToInitPage(listView, ctx)
            } catch (err) {
                console.log("测试打印===err===" + err)
            }
        }, 200)
    },
    onPageShow() {
        const ctx = this

        setTimeout(function () {
            try {
                let listView = ctx.$element("list-view")
                let option = new config(TypeEnum.data.TYPE_SEND_PARENT_WIDTH, ctx.currentPage, ctx.itemWidth, {}, {
                    id: ctx.localId,
                    parentWidth: listView.getBoundingClientRect().width
                })
                ctx.$emit("eventType1", option)
                ctx.scrollToInitPage(listView, ctx)

            } catch (err) {
                console.log("测试打印===err===" + err)
            }
        }, 200)
    },
    scrollToInitPage(listView, ctx) {
        listView.scrollTo({
            index: ctx.currentPage
        })
        ctx.centerX = listView.getBoundingClientRect().width / 2
        ctx.getItemSpace()

        let option = new config(TypeEnum.data.TYPE_REFRESH_ITEM, ctx.currentPage, ctx.itemWidth, {}, {
            id: ctx.localId,
            type: TypeEnum.data.TYPE_REFRESH_ITEM,
            currentPage: ctx.currentPage,
            scrollX: 0
        })
        ctx.$emit("eventType1", option)
    },
    getItemSpace() {
        const ctx = this
        let nextIndex = (ctx.currentPage + 1) >= (ctx.lists.length - 1) ? (ctx.lists.length - 1) : (ctx.currentPage + 1)
        let currentItem = ctx.$element("item-" + ctx.currentPage)
        let nextItem = ctx.$element("item-" + nextIndex)
        let currentCenter = currentItem.getBoundingClientRect().left + currentItem.getBoundingClientRect().width / 2
        let nextCenter = nextItem.getBoundingClientRect().left + nextItem.getBoundingClientRect().width / 2
        ctx.itemSpace = Math.abs(currentCenter - nextCenter)

    },
    getCurrentPage() {
        return this.currentPage
    },
    setCurrentPage(nowPage) {
        const that = this
        if (nowPage == undefined || that.lists.length == undefined
        || nowPage >= (that.lists.length - 1) || nowPage < 0) {
            return
        }
        that.currentPage = nowPage
        that.refreshCacheData()

    },
    initData() {
        const that = this
        try {
            that.lists.splice(0)
            that.lists = that.swiperDatas
            that.currentPage = that.currentIndex
            that.localId = that.diyId
            if (that.itemPercent >= 40) {
                that.percent = that.itemPercent
            } else {
                that.percent = 40
            }
            if (that.itemMargin <= 90) {
                that.margin = that.itemMargin
            } else {
                that.margin = 90
            }
        } catch (err) {
            that.lists = new Array()
        }
    },
    unionScroll(distance=0, id="", scrollState=0) {
        if (id == null || id == undefined || id != this.localId) {
            return
        }
        if (scrollState != 0) {
            this.isUnionScroll = true
            let listView = this.$element("list-view")
            listView.scrollBy({
                smooth: false,
                dy: 0,
                dx: distance
            })
        } else {
            this.isUnionScroll = false
            this.findCurrentItems()
            this.moveCurrentToCenter()
        }


    },
    refreshMargin(value) {
        this.margin = value
        console.log("测试打印===margin===" + this.margin)
    },
    refreshCacheData() {
        try {

        } catch (err) {
            console.log("测试打印===refreshCacheData===" + err)
        }
    },
    dispatchTouchStart(e) {
        if (e == null || e.touches == null || e.touches.length < 1) {
            return
        }

        const ctx = this
        ctx.startX = e.touches[0].localX
        ctx.startY = e.touches[0].localY
        let optionStart = new config(TypeEnum.data.TYPE_TOUCH_START, ctx.currentPage, ctx.itemWidth, {}, {})
        ctx.$emit("eventType1", optionStart)
    },
    dispatchTouchMove(e) {
        const ctx = this
        if (e == null || e.touches == null || e.touches.length < 1) {
            return
        }
        let optionMove = new config(TypeEnum.data.TYPE_TOUCH_MOVE, ctx.currentPage, ctx.itemWidth, {}, {})
        ctx.$emit("eventType1", optionMove)

        let moveX = e.touches[0].localX - ctx.startX
        let moveY = e.touches[0].localY - ctx.startY
        if (Math.abs(moveY) >= Math.abs(moveX)) {
            ctx.canNotScroll = true
        } else {
            ctx.canNotScroll = false
            let option = new config(TypeEnum.data.TYPE_UNION_SCROLL, ctx.currentPage, ctx.itemWidth, {}, {
                id: ctx.localId,
                currentPage: this.currentPage,
                scrollX: moveX,
                scrollState: 1,
            })
            this.$emit("eventType1", option)
        }

    },
    dispatchTouchCancel(e) {
        const ctx = this
        ctx.canNotScroll = false
        let optionCancel = new config(TypeEnum.data.TYPE_TOUCH_CANCEL, ctx.currentPage, ctx.itemWidth, {}, {})
        ctx.$emit("eventType1", optionCancel)

        let option = new config(TypeEnum.data.TYPE_UNION_SCROLL, ctx.currentPage, ctx.itemWidth, {}, {
            id: ctx.localId,
            currentPage: this.currentPage,
            scrollX: 0,
            scrollState: 0,
        })
        this.$emit("eventType1", option)
    },
    dispatchTouchEnd(e) {
        const ctx = this
        ctx.canNotScroll = false
        let optionEnd = new config(TypeEnum.data.TYPE_TOUCH_END, ctx.currentPage, ctx.itemWidth, {}, {})
        ctx.$emit("eventType1", optionEnd)

        let option = new config(TypeEnum.data.TYPE_UNION_SCROLL, ctx.currentPage, ctx.itemWidth, {}, {
            id: ctx.localId,
            currentPage: this.currentPage,
            scrollX: 0,
            scrollState: 0,
        })
        this.$emit("eventType1", option)
        if (e == null || e.touches == null || e.touches.length < 1) {
            return
        }

    },
    dispatchScroll(e) {
        if (e == null || e == undefined) {
            return
        }
        const ctx = this
        ctx.findCurrentItems()
        if (e.scrollState == 0) {
            if (!ctx.isUnionScroll) {
                ctx.moveCurrentToCenter()
            }
            let option = new config(TypeEnum.data.TYPE_SCROLL_END, ctx.currentPage, ctx.itemWidth, {}, {})
            ctx.$emit("eventType1", option)
        } else if (e.scrollState == 1) {
            let option = new config(TypeEnum.data.TYPE_SCROLLING, ctx.currentPage, ctx.itemWidth, {}, {})
            ctx.$emit("eventType1", option)
        } else if (e.scrollState == 2) {
            let option = new config(TypeEnum.data.TYPE_SCROLL_FLING, ctx.currentPage, ctx.itemWidth, {}, {})
            ctx.$emit("eventType1", option)
        }

    },
    moveCurrentToCenter() {
        const ctx = this
        let listView = ctx.$element("list-view")
        let item = ctx.$element("item-" + ctx.currentPage)
        let left = item.getBoundingClientRect().left
        let itemCenter = left + ctx.itemWidth / 2
        let offset = itemCenter - ctx.centerX
        if (offset == 0) {
            return
        }
        listView.scrollBy({
            smooth: false,
            dy: 0,
            dx: offset
        })
    },
    findCurrentItems() {
        const ctx = this
        var tempCurrent = ctx.currentPage;
        var tempOffset = ctx.centerX;
        for (var i = 0; i < ctx.lists.length; i++) {
            let item = ctx.$element("item-" + i)
            let left = item.getBoundingClientRect().left
            if (ctx.itemWidth == 0) {
                ctx.itemWidth = item.getBoundingClientRect().width - ctx.margin
            }
            if (left == 0) {
                continue
            }
            try {
                let itemCenterX = left + ctx.itemWidth / 2
                let offset = Math.abs(ctx.centerX - itemCenterX)
                if (offset < tempOffset) {
                    tempOffset = offset
                    tempCurrent = i
                }
            } catch (err) {
                console.log("测试打印===err===" + err)
            }
        }
        if (ctx.currentPage != tempCurrent) {
            ctx.currentPage = tempCurrent
            let option = new config(TypeEnum.data.TYPE_REFRESH_ITEM, ctx.currentPage, ctx.itemWidth, {}, {
                id: ctx.localId,
                currentPage: ctx.currentPage,
            })
            ctx.$emit("eventType1", option)
        }
        this.calculateScrollValue()
    },
    calculateScrollValue() {
        const ctx = this
        let lastIndex = (ctx.currentPage - 1) < 0 ? 0 : (ctx.currentPage - 1)
        let nextIndex = (ctx.currentPage + 1) >= (ctx.lists.length - 1) ? (ctx.lists.length - 1) : (ctx.currentPage + 1)

        let lastItem = ctx.$element("item-" + lastIndex)
        let currentItem = ctx.$element("item-" + ctx.currentPage)
        let nextItem = ctx.$element("item-" + nextIndex)

        let lastCenter = lastItem.getBoundingClientRect().left + ctx.itemWidth / 2
        let currentCenter = currentItem.getBoundingClientRect().left + ctx.itemWidth / 2
        let nextCenter = nextItem.getBoundingClientRect().left + ctx.itemWidth / 2

        let param = new scrollParam(lastCenter, currentCenter, nextCenter, ctx.itemSpace, ctx.centerX)
        let option = new config(TypeEnum.data.TYPE_ANIMATE, ctx.currentPage, ctx.itemWidth, param, {
            id: ctx.localId
        })
        ctx.$emit("eventType1", option)
    },
}
